package com.chookss.home.studyPlan;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.document.DocumentSearchActivity;
import com.chookss.home.entity.StudyListEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoOnePlayActivity;
import com.chookss.video.VideoSetsPlayActivity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.recommend.VedioDetailActivity;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StudyPlanTaskDetailActivity extends BaseAct {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.rlTitle)
    RelativeLayout rlTitle;
    @BindView(R.id.tvReleaseName)
    TextView tvReleaseName;
    @BindView(R.id.tvReleaseTime)
    TextView tvReleaseTime;

    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvComplete)
    TextView tvComplete;
    @BindView(R.id.tvReleaseDesc)
    TextView tvReleaseDesc;
    private String planCode;
    private String planStatus;//1未开始2进行中3已结束
    private String currentTime; //当前时间
    private String effTime, invalidTime; //计划开始结束时间
    private List<StudyListEntity.TbKmerStudyPlanTaskItemsBean> list = new ArrayList<>();
    private MyStudyAdapter myStudyAdapter;
    private String code1, code3; //一级页面底部的权限

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_my_study_task_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this,"1","04");
        code1 = new ShareUtils().getString(StudyPlanTaskDetailActivity.this, StaticClass.BOTTOM_1_CODE, "");
        code3 = new ShareUtils().getString(StudyPlanTaskDetailActivity.this, StaticClass.BOTTOM_3_CODE, "");
        planCode = getIntent().getStringExtra("planCode");
        effTime = getIntent().getStringExtra("effTime");
        invalidTime = getIntent().getStringExtra("invalidTime");
        planStatus = getIntent().getStringExtra("planStatus");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        currentTime = simpleDateFormat.format(date);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlTitle.getLayoutParams();
        layoutParams.setMargins(0, Utils.getStatusBarHeight(this), 0, 0);
        rlTitle.setLayoutParams(layoutParams);
        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myStudyAdapter = new MyStudyAdapter(R.layout.item_study_list, this, list);
        rvView.setAdapter(myStudyAdapter);
        getData();
        // 可以自定义水印文字颜色、大小和旋转角度
        NavigationTools.setWaterMark(this, "8");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("planCode", planCode);
        map.put("cycle", "5");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<StudyListEntity>>() {
        }.getType(), null, Urls.getTaskDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<StudyListEntity>() {
            @Override
            public void onSuccess(StudyListEntity data) {
                if (tvTitle == null||data==null) {
                    return;
                }
                tvTitle.setText(data.getPlanTitle());
                tvComplete.setText("完成：" + data.getTotalCompleteNum() + "/" + data.getTotalTargetNum());
                tvReleaseName.setText("发布人：" + data.getEmployeeName());
                tvReleaseDesc.setText(data.getPlanDesc());
                tvReleaseTime.setText(Utils.getAccurateDate(data.getCreateTime()));
                effTime = data.getEffTime();
                invalidTime = data.getInvalidTime();
                tvTime.setText("时间：" + Utils.clearZeroDay(data.getEffTime()) + "-" + Utils.clearZeroDay(data.getInvalidTime()));
                list.clear();
                list.addAll(data.getTbKmerStudyPlanTaskItems());
                myStudyAdapter.notifyDataSetChanged();

            }

            @Override
            public void onError(String errorMsg) {

                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    class MyStudyAdapter extends BaseQuickAdapter<StudyListEntity.TbKmerStudyPlanTaskItemsBean, BaseViewHolder> {
        private Context context;

        public MyStudyAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<StudyListEntity.TbKmerStudyPlanTaskItemsBean> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolder helper, StudyListEntity.TbKmerStudyPlanTaskItemsBean item) {
            ImageView ivStudy = helper.getView(R.id.ivStudy);
            TextView tvStudyName = helper.getView(R.id.tvStudyName);
            TextView tvStudy = helper.getView(R.id.tvStudy);
            TextView tvStudySure = helper.getView(R.id.tvStudySure);
            tvStudyName.setText(item.getTaskName());
//            任务类型（1-小视频 2-长视频 3-集合 4-课程 5 资料）
            tvStudy.setText("已完成" + item.getCompleteNum() + "/" + item.getTargetNum());
            if ("1".equals(item.getConnectType())) {
                Glide.with(context).load(R.drawable.icon_shipin).into(ivStudy);
            } else if ("2".equals(item.getConnectType())) {
                Glide.with(context).load(R.drawable.icon_fbsp).into(ivStudy);
            } else if ("3".equals(item.getConnectType())) {
                Glide.with(context).load(R.drawable.icon_jihe).into(ivStudy);
            } else if ("4".equals(item.getConnectType())) {
                Glide.with(context).load(R.drawable.icon_kecheng).into(ivStudy);
            } else if ("5".equals(item.getConnectType())) {
                Glide.with(context).load(R.drawable.icon_ziliao).into(ivStudy);
            } else {
                Glide.with(context).load(R.drawable.default_news).into(ivStudy);
            }
            int complete = Utils.changeNumber(item.getCompleteNum());
            int target = Utils.changeNumber(item.getTargetNum());
            int timeCompare = Utils.getTimeCompareSize(currentTime, effTime, invalidTime);
            if ("1".equals(item.getConnectType()) || "2".equals(item.getConnectType()) || "5".equals(item.getConnectType())) {
                if (3 == timeCompare) {
                    //还未开始
                    tvStudySure.setVisibility(View.GONE);
                } else if (1 == timeCompare) {
                    //已经结束
                    if ("1".equals(item.getCompleteFlag())) {
                        tvStudySure.setText("已完成");
                        tvStudySure.setSelected(true);
                        tvStudy.setText("已完成" + item.getTargetNum() + "/" + item.getTargetNum());
                    } else {
                        tvStudySure.setText("未完成");
                        tvStudySure.setSelected(true);
                    }
                    tvStudySure.setVisibility(View.VISIBLE);
                } else {
                    if ("1".equals(item.getCompleteFlag())) {
                        tvStudySure.setText("已完成");
                        tvStudySure.setSelected(true);
                        tvStudy.setText("已完成" + item.getTargetNum() + "/" + item.getTargetNum());
                    } else {
                        tvStudySure.setText("去完成");
                        tvStudySure.setSelected(false);
                    }
                    tvStudySure.setVisibility(View.VISIBLE);
                }
            } else {
                if (3 == timeCompare) {
                    //还未开始
                    tvStudySure.setVisibility(View.GONE);
                } else if (1 == timeCompare) {
                    //已经结束
                    if (complete >= target) {
                        tvStudySure.setText("已完成");
                        tvStudySure.setSelected(true);
                        tvStudy.setText("已完成" + item.getTargetNum() + "/" + item.getTargetNum());
                    } else {
                        tvStudySure.setText("未完成");
                        tvStudySure.setSelected(true);
                    }
                    tvStudySure.setVisibility(View.VISIBLE);
                } else {
                    if (complete >= target) {
                        tvStudySure.setText("已完成");
                        tvStudySure.setSelected(true);
                        tvStudy.setText("已完成" + item.getTargetNum() + "/" + item.getTargetNum());
                    } else {
                        tvStudySure.setText("去完成");
                        tvStudySure.setSelected(false);
                    }
                    tvStudySure.setVisibility(View.VISIBLE);
                }

            }

            tvStudySure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    if (tvStudySure.getText().toString().contains("去完成")) {
                    //            任务类型（1-小视频 2-长视频 3-集合 4-课程 5 资料）
                    if(Utils.changeNumber(item.getTargetNum())<=0){
                        MyToast.show("数据异常，请联系管理员");
                        return;
                    }
                    if ("1".equals(item.getConnectType())) {
                        getViedeo(item.getTaskCode(), item.getConnectType());
                    } else if ("2".equals(item.getConnectType())) {
                        getViedeo(item.getTaskCode(), item.getConnectType());
                    } else if ("3".equals(item.getConnectType())) {
                        getViedeoNum(item.getTaskCode(), item.getConnectType());
                    } else if ("4".equals(item.getConnectType())) {
                        getViedeoNum(item.getTaskCode(), item.getConnectType());
                    } else if ("5".equals(item.getConnectType())) {
                        if (PermissionSpUtils.getBoolean(StudyPlanTaskDetailActivity.this,"03",false)) {
                            Intent intent = new Intent(StudyPlanTaskDetailActivity.this, DocumentSearchActivity.class);
                            intent.putExtra("dataCode", item.getTaskCode());
                            intent.putExtra("type", 1);
                            startActivity(intent);
                        } else {
                            MyToast.show("管理员已关闭资料库功能");
                        }
                    }
                }
            });
        }
    }

    private void getViedeo(String id, String connectType) {
        if (!PermissionSpUtils.getBoolean(this,"14",false)) {
            MyToast.show("管理员已关闭视频功能");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("videoId", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectAPPVideoById, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                Intent intent = null;
                if ("1".equals(connectType)) {
                    intent = new Intent(StudyPlanTaskDetailActivity.this, VideoOnePlayActivity.class);
                    intent.putExtra("watermark", "2");
                } else {
                    intent = new Intent(StudyPlanTaskDetailActivity.this, VedioDetailActivity.class);
                    intent.putExtra("watermark", "20");
                    intent.putExtra("source", 1);
                }
                intent.putExtra("video", data);
                startActivity(intent);
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getViedeoNum(String id, String connectType) {
        if (!PermissionSpUtils.getBoolean(this,"14",false)) {
            MyToast.show("管理员已关闭视频功能");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("connectCode", id);
        map.put("connectType", connectType);
        map.put("effTime", effTime.substring(0, 10));
        map.put("invalidTime", invalidTime.substring(0, 10));
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectUncompleteVideo, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                Intent intent = null;
                if ("3".equals(connectType)) {
                    intent = new Intent(StudyPlanTaskDetailActivity.this, VideoSetsPlayActivity.class);
                    intent.putExtra("watermark", "4");
                    intent.putExtra("type", "4");
                } else {
                    intent = new Intent(StudyPlanTaskDetailActivity.this, VedioDetailActivity.class);
                    intent.putExtra("watermark", "20");
                    intent.putExtra("source", 2);
                }
                intent.putExtra("video", data);
                intent.putExtra("effTime", effTime.substring(0, 10));
                intent.putExtra("invalidTime", invalidTime.substring(0, 10));
                startActivity(intent);
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @OnClick({R.id.ivBack})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
        }
    }
}
